//
//  EmojiPictureUtils.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/10/16.
//

import Foundation
import LeanCloud
class EmojiPictureUtils {
    static let shared = EmojiPictureUtils()
    private var emojiPicture: [String:EmojiPictureBean]? = nil //表情包
    private func log(_ msg: String) {
        print("emojiPicture", msg)
    }
    
    private func getEmojiPicture() -> [String:EmojiPictureBean] {
        if (emojiPicture == nil) {
            let json = AppStorageManager.shared.aiEmojiPicture
            if (json.isEmpty == true) {
                emojiPicture = [:]
            } else {
                let map = try? fromJson(json,[String: EmojiPictureBean].self)
                emojiPicture = map
                log("获取缓存数据")
            }
        }
        return emojiPicture ?? [:]
    }
    
    private func addEmojiPicture(key: String, bean: EmojiPictureBean) {
        if (emojiPicture == nil) {
            emojiPicture = [:]
        }
        do {
            emojiPicture?[key] = bean
            AppStorageManager.shared.aiEmojiPicture = toJson(emojiPicture) ?? "{}"
        }
        
    }
    
    func getEmojiPicture(key: String) async throws -> EmojiPictureBean? {
        var bean = getEmojiPicture()[key]
        if (bean == nil) {
            bean = try await getEmojiPictureBean(key: key)
        }
        if let bean = bean {
            addEmojiPicture(key: key, bean: bean)
        }
        return bean
    }
    
    private func getEmojiPictureBean(key: String) async throws -> EmojiPictureBean? {
        log("网络请求表情包：\(key)")
        let bean = try await retry(maxRetries: 3, retryDelayMillis: 100) {
            let query = LCQuery(className: "EmojiPicture")
            query.whereKey("key", .equalTo(key))
            return try await LeancloudManager.instance.getFirst(query: query, modeType: EmojiPictureBean.self)
        }
        return bean
    }
    
    func delEmojiPicture() {
        if (configManager.getConfig().getSwitchConfig().isUpdateEmojiPicture) {
             log("清空缓存")
             //清空缓存
            AppStorageManager.shared.aiEmojiPicture = "{}"
         }
     }
    
    //是否含有EmojiPicture，并且提取第一个
    func containsEmojiPicture(_ text: String) -> String? {
        // 正则表达式匹配 {{}} 及其中的内容（非贪婪模式，确保只匹配第一个）
        let pattern = "\\{\\{.*?\\}\\}|【.*?】" // 同时匹配 {{}} 和 【】
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return nil
        }
        
        // 在文本中查找第一个匹配项
        let nsText = text as NSString
        let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        
        // 返回第一个匹配到的内容，若没有则返回 nil
        if let firstMatch = matches.first {
            let range = firstMatch.range
            return nsText.substring(with: range)
        }
        return nil
    }
    
    //EmojiPictureBean 转为为可以显示的MediaItem 试图
    func getMediaItem(_ pictrue: EmojiPictureBean?)-> MediaItem? {
        if pictrue == nil {
            return nil
        }
        var mediaItems : MediaItem? = nil
        if pictrue?.path?.isUrl() == true {
            let item = MediaItem(type: .networkImage(pictrue!.path ?? "",pictrue!.path ?? "", pictrue!.isVideo()))
            mediaItems = item
        } else {
            if pictrue?.isVideo() == true {
                //视频
                if let url = VideoFileManager.loadVideoURL(pictrue!.path ?? "") {
                    let item = MediaItem(type: .localVideo(url))
                    mediaItems = item
                }
            } else {
                //图片
                if let localPath = ImageFileManager.loadImagePath(pictrue!.path ?? ""), !localPath.isEmpty {
                       mediaItems = MediaItem(type: .localImagePath(localPath))
                   } else if let image = ImageFileManager.loadImage(pictrue!.path ?? "") {
                       // 路径无效，尝试加载图片
                       mediaItems = MediaItem(type: .localImage(image))
                   }
            }
        }
        return mediaItems
    }
}
